package action;

import java.sql.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import utils.Common;
import utils.XmlReplace;

public class Action{
	public String insert(HttpServletRequest req, HttpServletResponse res,Connection conn){
		String xml = "";
		PreparedStatement stmt = null;
		try {
			String username = req.getParameter("uid");
			String password = req.getParameter("fullname");
			String sql = "INSERT INTO user(userid,fullname) values (?,?) ";
			stmt = conn.prepareStatement(sql);
			stmt.setString(1, username);
			stmt.setString(2, password);
			if (stmt.executeUpdate() == 1){
				xml = Common.makeSuccessXML();
			} else {
				xml = Common.makeErrorXML("Insert fail");
			}
			
		} catch (Exception e) {
			e.printStackTrace();
			xml = Common.makeErrorXML("Insert fail");
		} finally {
			try {if (stmt != null) stmt.close();} catch (SQLException e) {}
		}
		return xml;
	}
	
	public String list(HttpServletRequest req, HttpServletResponse res,Connection conn){
		String xml = "";
		PreparedStatement stmt = null;
		ResultSet rs = null;
		try {
			
			String sql = "SELECT * FROM user";
			stmt = conn.prepareStatement(sql);
			rs = stmt.executeQuery();
			while(rs.next()){
				xml += "<user uid=\""+XmlReplace.escape(rs.getString("userid"))+"\" " +
						"fullname=\""+XmlReplace.escape(rs.getString("fullname"))+"\" " +
						"/>";
			}
			xml = Common.makeSuccessXML(xml);
			
		} catch (Exception e) {
			e.printStackTrace();
			xml = Common.makeErrorXML("List fail");
		} finally {
			try {if (rs != null) rs.close();} catch (SQLException e) {}
			try {if (stmt != null) stmt.close();} catch (SQLException e) {}
		}
		return xml;
	}
	public String delete(HttpServletRequest req, HttpServletResponse res, Connection conn){
		String xml = "";
		PreparedStatement stmt = null;
		try {
			String userid = req.getParameter("uid");
			String sql = "DELETE FROM user WHERE userid = ?";
			stmt = conn.prepareStatement(sql);
			stmt.setString(1, userid);
			if(stmt.executeUpdate()>0){
				return Common.makeSuccessXML();
			}else{
				return Common.makeErrorXML("Error");
			}
		} catch (Exception e) {
			e.printStackTrace();
			xml = Common.makeErrorXML("Delete fail");
		} finally {
			try {if (stmt != null) stmt.close();} catch (SQLException e) {}
		}
		return xml;
	}
}